package iconeLibrary.model;

import iconeLibrary.model.XQueryRequest;
import iconeLibrary.view.IconeLibraryServlet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XQueryService;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Ayede Sonia :: Gaudino Anthony :: Herche Bilal :: Teixeira Tiago :: Touati Samed  :: Wadjahdi Marc
 */
public class Connection {

    private static Collection col;
    private XQueryRequest xQueryRequest;

    /**
     * Method that create a connection to an exist database .
     * @param eXistURL
     * @param login
     * @param password
     * @return the XQuery Service 
     * @throws XMLDBException
     */
    public void CreateConnection(String eXistURL, String login, String password) throws XMLDBException {
        try {
            String driver = "org.exist.xmldb.DatabaseImpl";
            Class cl = Class.forName(driver);
            Database database1 = (Database) cl.newInstance();
            DatabaseManager.registerDatabase(database1);
            col = DatabaseManager.getCollection(eXistURL, "admin", "admin");
            col = col.getChildCollection("IconeLibraryBD");
            xQueryRequest = new XQueryRequest((XQueryService) col.getService("XQueryService", "1.0"));
        } catch (InstantiationException ex) {
            Logger.getLogger(IconeLibraryServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(IconeLibraryServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(IconeLibraryServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public XQueryRequest getXQueryRequest(){
        return xQueryRequest;
    }
    /**
     * Method that close the connection at the database .
     */
    public void closeConnection() {
        try {
            col.close();
        } catch (XMLDBException ex) {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
